<template>
  <div class="white-box" v-loading.fullscreen="loading">
    <el-form ref="formRef" :model="formData" :rules="formRule" label-width="150px">

      <el-form-item label="房产编号" prop="rent_house_sn">
        <el-input v-model.trim="formData.rent_house_sn" clearable placeholder="请输入房产编号"/>
      </el-form-item>
      <el-form-item label="房产标题" prop="title">
        <el-input v-model.trim="formData.title" clearable placeholder="请输入房产标题"/>
      </el-form-item>
      <el-form-item label="小区" prop="min_area_id">
        <el-select v-model="formData.min_area_id" placeholder="请选择小区" @change="min_area_id_change">
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.min_area_id" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="X栋X单元X层X室" prop="addr">
        <div v-loading="minAreaShiNoLoading" element-loading-background="rgba(122, 122, 122, 0.4)">
          <el-cascader v-model="formData.addr" :props="{value:'title',label:'label'}" :options="minAreaShiNoOptions" @change="handleMinAreaShiNoChange" />
        </div>
      </el-form-item>
      <el-form-item label="出租方式" prop="chuzu_id">
        <el-select v-model="formData.chuzu_id" placeholder="请选择出租方式">
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.chuzu_id" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="期望租金" prop="expect_rent_price">
        <el-input v-model.trim="formData.expect_rent_price" clearable placeholder="请输入期望租金" oninput="value=value.replace(/[^\d.]/g,'')">
          <template #append>元/月</template>
        </el-input>
      </el-form-item>
      <el-form-item label="支付类型" prop="pay_type_id">
        <el-select v-model="formData.pay_type_id" placeholder="请选择支付类型">
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.pay_type_id" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入住时间" prop="in_time">
        <el-date-picker
            v-model="formData.in_time"
            type="date"
            placeholder="选择入住时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="link_name">
        <el-input v-model.trim="formData.link_name" clearable placeholder="请输入联系人"/>
      </el-form-item>
      <el-form-item label="联系人方式" prop="link_tel">
        <el-input v-model.trim="formData.link_tel" clearable placeholder="请输入联系人方式" oninput="value=value.replace(/[^\d]/g,'')"/>
      </el-form-item>
      <el-form-item label="面积" prop="area_num">
        <el-input v-model.trim="formData.area_num" clearable placeholder="请输入面积" oninput="value=value.replace(/[^\d.]/g,'')">
          <template #append>平方米</template>
        </el-input>
      </el-form-item>
      <el-form-item label="楼层高度" prop="loucen_grade_id">
        <el-radio-group v-model="formData.loucen_grade_id">
          <el-radio :label="1">高</el-radio>
          <el-radio :label="2">中</el-radio>
          <el-radio :label="3">低</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="楼层" prop="loucen_num">
        <el-input v-model.trim="formData.loucen_num" clearable placeholder="请输入楼层" oninput="value=value.replace(/[^\d]/g,'')" />
      </el-form-item>
      <el-form-item label="X室" prop="shi_num">
        <el-input v-model.trim="formData.shi_num" clearable placeholder="请输入X室" oninput="value=value.replace(/[^\d]/g,'')" />
      </el-form-item>
      <el-form-item label="X厅" prop="ting_num">
        <el-input v-model.trim="formData.ting_num" clearable placeholder="请输入X厅" oninput="value=value.replace(/[^\d]/g,'')" />
      </el-form-item>
      <el-form-item label="X卫" prop="wei_num">
        <el-input v-model.trim="formData.wei_num" clearable placeholder="请输入X卫" oninput="value=value.replace(/[^\d]/g,'')" />
      </el-form-item>
      <el-form-item label="朝向" prop="chaoxiang_id">
        <el-select v-model="formData.chaoxiang_id" placeholder="请选择朝向">
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.chaoxiang_id" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="是否有电梯" prop="is_elevator">
        <el-radio-group v-model="formData.is_elevator">
          <el-radio :label="1">有</el-radio>
          <el-radio :label="2">无</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="房间类型" prop="room_type_id">
        <el-radio-group v-model="formData.room_type_id">
          <el-radio :label="1">主卧</el-radio>
          <el-radio :label="2">次卧</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="房屋配套" prop="peitao_id">
        <el-select v-model="formData.peitao_id" placeholder="请选择朝向" multiple>
          <el-option :label="item.label" :value="item.value" v-for="(item, index) in selectOptions.peitao_id" :key="index"/>
        </el-select>
      </el-form-item>
      <el-form-item label="户型图" prop="img1">
        <File-Oss-upload v-model="formData.img1" :fileSize="50" :limit="9" :fileType="['png', 'jpg', 'jpeg']" listType="picture-card"></File-Oss-upload>
      </el-form-item>
      <el-form-item label="房间照片" prop="img2">
        <File-Oss-upload v-model="formData.img2" :fileSize="50" :limit="9" :fileType="['png', 'jpg', 'jpeg']" listType="picture-card"></File-Oss-upload>
      </el-form-item>
      <el-form-item label="环境照片" prop="img3">
        <File-Oss-upload v-model="formData.img3" :fileSize="50" :limit="9" :fileType="['png', 'jpg', 'jpeg']" listType="picture-card"></File-Oss-upload>
      </el-form-item>
      <el-form-item label="是否推荐" prop="is_tuijian">
        <el-radio-group v-model="formData.is_tuijian">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">不是</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <div class="foot-btn flexs-center" style="margin-top: 30px">
          <el-button type="primary" size="large" :loading="btnLoading" @click="submitForm(formRef)">{{rent_house_id?'确认修改':'确认添加'}}</el-button>
        </div>
      </el-form-item>
    </el-form>

    <go-back/>
  </div>
</template>

<script setup>
import {getCurrentInstance, ref, onMounted, shallowRef, reactive, onBeforeUnmount, watch} from "vue"
import {useRouter, useRoute} from "vue-router"
import {UploadFilled, CloseBold,Plus} from "@element-plus/icons-vue"
import GoBack from "@components/GoBack.vue"
import "@wangeditor/editor/dist/css/style.css"
import FileOssUpload from "@/components/FileOssUpload.vue"
import {validNumOrPoint} from "@common/utils";

const router = useRouter()
const route = useRoute()
const {proxy} = getCurrentInstance()

const rent_house_id = route.query.rent_house_id || ""

onMounted(() => {
  getSelectOptions()
  if (rent_house_id) {
    getDetail()
  }
})
/**
 * 添加
 * @param {Boolean} btnLoading 提交按钮状态
 * @param {Array} formRef 表单规则
 * @param {Object} formData  表单字段
 * @param {Object} formRule  表单提示
 * @param {Function} submitForm 提交表单
 */
const btnLoading = ref(false)
const loading = ref(false)
const formRef = ref(null)
const formData = reactive({
  rent_house_sn: '',
  title: '',
  min_area_id: '',
  chuzu_id: '',
  expect_rent_price: '',
  pay_type_id: '',
  in_time: '',
  link_name: '',
  link_tel: '',
  area_num: '',
  loucen_grade_id: '',
  loucen_num: '',
  rongji_ratio: '',
  shi_num: '',
  ting_num:'',
  wei_num:'',
  chaoxiang_id:'',
  is_elevator:1,
  room_type_id:1,
  peitao_id:[],
  is_tuijian:1,
  img1:[],
  img2:[],
  img3:[],
  addr:[],
  dong_sn:'',
  unit_sn:'',
  layer_sn:'',
  house_sn:'',
})

const minAreaShiNoOptions = ref([]);
const minAreaShiNoLoading = ref(false)
const handleMinAreaShiNoChange = (e) =>{
  formData.dong_sn = e[0];
  formData.unit_sn = e[1];
  formData.layer_sn = e[2];
  formData.house_sn = e[3];
}
const min_area_id_change = (e) =>{
  // console.log('min_area_id_change',e);
  formData.addr = [];
  formData.dong_sn = '';
  formData.unit_sn = '';
  formData.layer_sn = '';
  formData.house_sn = '';
  minAreaShiNoOptions.value = [];
  getMinAreaShiNo()
}

const detail = reactive({})
if(rent_house_id){
  formData.rent_house_id = rent_house_id
}

const formRule = reactive({
  rent_house_sn: [{required: true, message: "请输入房产编号", trigger: "blur"}],
  title: [{required: true, message: "请输入房产标题", trigger: "blur"}],
  min_area_id: [{required: true, message: "请选择小区", trigger: "change"}],
  chuzu_id: [{required: true, message: "请选择出租方式", trigger: "change"}],
  expect_rent_price: [{required: true, message: "请输入期望租金", trigger: "blur"},{validator:proxy.$util.validNumOrPoint,trigger: "blur"}],
  pay_type_id: [{required: true, message: "请选择支付类型", trigger: "change"}],
  in_time: [{required: true, message: "请选择入住时间", trigger: "change"}],
  link_name: [{required: true, message: "请输入联系人", trigger: "blur"}],
  link_tel: [{required: true, message: "请输入联系人手机号",trigger: "blur"},{validator: proxy.$util.validPhone,trigger: "blur"}],
  area_num: [{required: true, message: "请输入面积", trigger: "blur"},{validator:proxy.$util.validNumOrPoint,trigger: "blur"}],
  loucen_grade_id: [{required: true, message: "请选择楼层高度", trigger: "change"}],
  loucen_num: [{required: true, message: "请输入楼层", trigger: "blur"}],
  shi_num: [{required: true, message: "请输入X室", trigger: "blur"}],
  ting_num:[{required: true, message: "请输入X厅", trigger: "blur"}],
  wei_num:[{required: true, message: "请输入X卫", trigger: "blur"}],
  chaoxiang_id:[{required: true, message: "请选择朝向", trigger: "change"}],
  is_elevator:[{required: true, message: "请选择是否有电梯", trigger: "change"}],
  room_type_id:[{required: true, message: "请选择房间类型", trigger: "change"}],
  peitao_id:[{required: true, message: "请选择房屋配套", trigger: "change"}],
  is_tuijian:[{required: true, message: "请选择是否推荐", trigger: "change"}],
  img1: [{required: true, message: "请选择户型图", trigger: "change"}],
  img2: [{required: true, message: "请选择样房间照片", trigger: "change"}],
  img3: [{required: true, message: "请选择样环境照片", trigger: "change"}],
  addr:[{required: true, message: "请选择具体单元栋数", trigger: ['change','blur']}],
})
const getDetail = () => {
  loading.value = true
  proxy.$axios
      .get("admin/house/rent/detail", {
        params: {
          rent_house_id: rent_house_id,
        },
      })
      .then((res) => {
        if (res.data.code == 200) {
          let result = res.data.data

          for (let key in formData) {
            formData[key] = result[key]
          }
          formData.in_time = result.in_time_label

          let {dong_sn,unit_sn,layer_sn,house_sn} = result
          formData.addr = [];
          formData.addr.push(dong_sn);
          formData.addr.push(unit_sn);
          formData.addr.push(layer_sn);
          formData.addr.push(house_sn);
          // console.log(formData.addr);
          getMinAreaShiNo()
        } else {
          proxy.$message({message: res.data.msg, type: "error"})
        }
      })
      .catch((err) => {

      }).finally(()=>{
        loading.value = false
      })
}
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      let data = {
        ...formData
      };
      delete data.addr
      let url = rent_house_id ?"admin/house/rent/update":"admin/house/rent/create"
      btnLoading.value = true
      proxy.$axios
          .post(url,data)
          .then((res) => {
            btnLoading.value = false
            if (res.data.code == 200) {
              proxy.$message({message: "保存成功！", type: "success",onClose:()=>router.go(-1)})

            } else {
              proxy.$message({message: res.data.msg, type: "error"})
            }
          })
          .catch((err) => {
            btnLoading.value = false
          })
    }
  })
}
const selectOptionsConfig = {
  min_area_id:{url:'common/dataSelect/minAreaSelect',params:{}},
  chuzu_id:{url:'common/dataSelect/houseTagSelect',params:{p_id:12}},
  pay_type_id:{url:'common/dataSelect/houseTagSelect',params:{p_id:11}},
  chaoxiang_id:{url:'common/dataSelect/houseTagSelect',params:{p_id:2}},
  peitao_id:{url:'common/dataSelect/houseTagSelect',params:{p_id:9}},

}
const selectOptions = reactive({
  min_area_id:[],
  chuzu_id:[],
  pay_type_id:[],
  chaoxiang_id:[],
  peitao_id:[]
})
const getSelectOptions = () => {
  for (let key in selectOptionsConfig){
    let {url,params} = selectOptionsConfig[key]
    proxy.$axios
        .get(url,{params:params})
        .then((res) => {
          if (res.data.code == 200) {
            let arr;
            if(url == 'common/dataSelect/houseTagSelect'){
              arr = res.data.data.map(item => {
                return {
                  label:item.house_tag_title,
                  value:item.house_tag_id,
                }
              })
            }
            if(url == 'common/dataSelect/minAreaSelect'){
              arr = res.data.data.map(item => {
                return {
                  label:item.min_area_title,
                  value:item.min_area_id,
                }
              })
            }
            selectOptions[key] = arr
          } else {
            proxy.$message({
              message: res.data.msg,
              type: "error"
            })
          }
        })
        .catch((err) => {
        })
  }
}
const getMinAreaShiNo = () => {
  let min_area_id = formData.min_area_id;
  minAreaShiNoLoading.value = true
  proxy.$axios
      .get('common/getMinAreaShiNo',{params:{min_area_id:min_area_id}})
      .then((res) => {
        if (res.data.code == 200) {
          let arr = res.data.data;
          setMinAreaShiNoOptionsLabel(arr)
          minAreaShiNoOptions.value = arr;
        } else {
          proxy.$message({
            message: res.data.msg,
            type: "error"
          })
        }
      })
      .catch((err) => {
      })
      .finally(()=>{
        minAreaShiNoLoading.value = false
      })
}
const handleLon = ()=> {
  window.open("https://lbs.qq.com/getPoint/");
}

const setMinAreaShiNoOptionsLabel = (arr,unit_name)=>{
  !unit_name && (unit_name ='栋');
  arr.forEach(item=>{
    item.label = item.title + unit_name
    if(item.children &&  item.children.length > 0){
      let _unit_name = unit_name == '栋' ?'单元':unit_name == '单元'?'层':unit_name == '层'?'室':''
      setMinAreaShiNoOptionsLabel(item.children,_unit_name)
    }
  })
}
</script>

<style lang="less" scoped>
///deep/.el-form .el-form-item__content .el-input, .el-form .el-form-item__content .el-textarea, .el-form .el-form-item__content .el-date-editor--datetime .el-input__wrapper {
//  width: 400px !important;
//}
</style>
